<template>
  <div>
    <div style="margin-bottom: 10px; margin-left: 10px">
      <label style="font-size: 30px; margin-right: 10px">排班表:</label>
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        value-format="yyyy-MM-dd"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
      >
      </el-date-picker>
      <el-button
        type="primary"
        style="margin-left: 10px; margin-right: 10px"
        @click="setArrangeWork"
        >查询</el-button
      >
      <CopyModal :show="showModal" @fanhui="closeModal" @fuzhi="fuzhi"></CopyModal>
    </div>
    <div>
      <el-row :gutter="24">
        <el-col :span="5">
          <el-table
            border
            height="400"    
            :cell-style="changeTaskStyle"       
            :data="dateTask"
          >
            <el-table-column fixed key="code" prop="code" label="符号">
            </el-table-column>
            <el-table-column fixed key="name" prop="name" label="班次名称">
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="19">
          <div>
            <el-table
              border
              max-height="400"
              fit             
              :data="arrangeWorkData"
              @cell-click="cellClick"
              v-loading="loadingbut"
              :cell-style="changeStyle"
            >
              <template>
                <el-table-column
                  fixed
                  style="word-break: keep-all !important;"
                  key="name"
                  prop="name"
                 
                  label="员工\日期"
                >
                </el-table-column>
                <el-table-column
                  v-for="col in dateColumns"
                  style="word-break: keep-all !important"
                  align="center"
                  :key="col.key"
                  :prop="col.key"
                  :label="col.title"
                  
                >
                </el-table-column>
              </template>
            </el-table>
          </div>
        </el-col>
      </el-row>
    </div>

    <el-dialog
        :title="addtitle"
        :visible.sync="dialogVisible"
        width="40%"
        append-to-body
        :before-close="handleClose"
      >
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="refRuleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="员工" prop="employeeName">
            <el-input v-model="ruleForm.employeeName" disabled></el-input>
          </el-form-item>
          <el-form-item label="日期" prop="date">
            <el-input v-model="ruleForm.date" disabled></el-input>
          </el-form-item>
          <el-form-item label="班次" prop="age">
          <el-select v-model="ruleForm.taskId">
            <el-option v-for="item in dateTask" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="danger" style="float:left" :disabled="isCreate" @click="deleteArrageWork">删除</el-button>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisibleConfirm"
            >确 定</el-button
          >
        </span>
      </el-dialog>
  </div>
</template>

<script>
import ajax from "@/lib/ajax";
import { Component, Vue, Inject, Prop, Watch } from "vue-property-decorator";
import CopyModal from '../arrangework/CopyTableTime'
export default {
  components: {
    CopyModal
  },
  data() {
    return {
      addtitle:"",
      showModal: false,
      isCreate: false,
      dialogVisible: false,
      tempToGetTName: { eName: '', dateStr: '' },
      checkKey: '',
      checkEname: '',
      dateRange: [],
      loadingbut: false, ///加载状态
      employeeList: [], ///search后动态生成最后赋给排班表数据源arrangeWorkData
      arrangeWorkOriginalList: [], ///查询出来的初始数据 字段：id 员工编号 班次 排班时间
      arrangeWorkData: [], ///排班表数据源
      dateColumns: [],
      dateTask: [],
      aid: '',
      rules: {
        name: [
          { required: true, message: "请输入学生姓名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        code: [{ required: true, message: "请输入学号", trigger: "blur" }],
      },
      ruleForm: {
        employeeName: "",
        employeeId: "",
        taskName: "",
        taskId: "",
        date: "",
      },
      pickerOptions: {
        disabledDate: (time) => {
          return this.dealDisabledDate(time);
        },
      },
    };
  },
  methods: {
    ///复制窗口的显示隐藏
    showCopyModal() {
      this.showModal = true
    },
    ///关闭弹窗
    closeModal() {
      this.showModal = false
    },
    ///编辑后重新执行下查询以刷新数据
    fuzhi(fanhuizhi) {
      this.setArrangeWork()
      this.showModal = false
    },
    changeTaskStyle({ row, column, rowIndex, columnIndex }) {
      return (
        "color:white;background-color:" + row.background_Color
      );     
    },
    
    ///排班表的样式 背景色
    changeStyle({ row, column, rowIndex, columnIndex }) {
      if (columnIndex == 0) {
        return 'color:black;'
      } else {
        if (row[column.property] == '') {
          return ''
        } else {
          var temp = this.dateTask.filter((item) => {
            // 以name来搜索
            return item.code === row[column.property]
          })

          var tempcolor = temp[0].background_Color
          return 'color:white;background-color:' + tempcolor
        }
      }
    },
    //设置可以选择的时间范围
    dealDisabledDate(time) {
      return (
        time.getTime() < new Date(this.dateRange[0]).getTime() ||
        time.getTime() > new Date(this.dateRange[1]).getTime()
      );
    },
    cellClick(row,column,event,cell) {
      console.log("eid:" + column.property)
	    ///员工列名的不触发点击事件
      if (column.property != 'employeeName') {
        this.ruleForm.employeeName = row.name;
         //this.aid = row.id; //把id存全局             
        this.ruleForm.date = column.property        
        this.ruleForm.employeeId = row.employeeId;
        if (row[column.property] == '' || row[column.property] == null) {
          this.addtitle ="新增排班";          
          this.ruleForm.taskId = this.dateTask[0].id;
          this.isCreate = true;
        } else {
           this.addtitle ="编辑排班";
          var empAndDateList = this.dateTask.filter((item) => {
            // 以name来搜索
            return item.code === row[column.property]
          })

          this.ruleForm.taskId = empAndDateList[0].id

          this.isCreate = false
        }
        this.dialogVisible  = true;
      }
    },
    // 确定
    dialogVisibleConfirm() {
      var that = this;
      // 新增接口
      if (this.isCreate) {
       
        ///true为新增
        ajax
          .post('/api/services/app/EmployeeTaskMapping/CreateArrangeWork', {
            employeeId: that.ruleForm.employeeId,
            DateStr: that.ruleForm.date,
            taskId: that.ruleForm.taskId
          })
          .then(function (res) {
            that.$message.success("添加成功");
            
            that.dialogVisible = false;
            that.initArrangeWork(); //刷新列表
          })
          .catch((res) => {
            that.$message.error("添加失败");
          });
      } else {
        // 修改接口
        ajax
          .put('/api/services/app/EmployeeTaskMapping/UpdateArrangeWork', {
            employeeId: that.ruleForm.employeeId,
            DateStr: that.ruleForm.date,
            taskId: that.ruleForm.taskId
          })
          .then(function (res) {
            that.$message.success("修改成功");
           
            that.dialogVisible = false;
            that.initArrangeWork(); //刷新列表
          })
          .catch((res) => {
            that.$message.error({ message: "修改失败", type: 'error' });
          });

        
      }
    },
    deleteArrageWork() {
      let that = this
      ajax
        .post('/api/services/app/EmployeeTaskMapping/DelArrangeWork', {
          employeeId: that.ruleForm.employeeId,
          DateStr: that.ruleForm.date,
          taskId: that.ruleForm.taskId
        })
        .then(function (res) {
          that.dialogVisible = false;
          that.initArrangeWork(); //刷新列表
          that.$message.success("删除成功");
        })
    },
    handleClose(done) {
      this.dialogVisible = false;
    },
    initArrangeWork() {
      let that = this;
      ajax
        .get("/api/services/app/EmployeeTaskMapping/GetStartTimeAndEndTime")
        .then(function (res) {
          that.dateRange = res.data.result;
          that.setArrangeWork()
        });
    },
    getAllTask() {
      let that = this;
      ajax
        .post("/api/services/app/Task/OutPutAllTask", { keyword: "" })
        .then(function (res) {
          that.dateTask = res.data.result;
        });
    },
    ///设置排班表
    setArrangeWork() {
      if (
        this.dateRange == null ||
        this.dateRange[0] == "" ||
        this.dateRange[1] == ""
      ) {
        this.$message({ message: "请正确选择排班时间范围", type: "error" });
      } else {
        this.arrangeWorkData = []; //清空排班数据
        this.loadingbut = true;

        var that = this;
        ajax
          .post("/api/services/app/EmployeeTaskMapping/OutputArrangeWork", {
            startDate: that.dateRange[0],
            endDate: that.dateRange[1],
          })
          .then(function (res) {
            that.arrangeWorkOriginalList = res.data.result;
            that.dateColumns = [];
            let start = new Date(that.dateRange[0]);
            let end = new Date(that.dateRange[1]);
            ///开始时间小于结束时间再添加表头
            if (start.getTime() <= end.getTime()) {
              that.addHead(start, end);
            }
            that.arrangeWorkData = that.employeeList;//给表格赋值
          });
      }
    },
    //添加排班表头和表数据
    addHead(start, end) {
        let headDate = new Date(start);       
        let headDay = headDate.getDay();
        
        let yy = headDate.getFullYear();
        let mm = headDate.getMonth() + 1 < 10 ? "0" + (headDate.getMonth() + 1) : headDate.getMonth() + 1;      
        let dd = headDate.getDate() < 10 ? "0" + headDate.getDate() : headDate.getDate();       
        let weeks = ["日", "一", "二", "三", "四", "五", "六"];
        let week = weeks[headDay]; //获取当前周几

        let workDate = yy + "-" + mm + "-" + dd;       
        this.dateColumns.push({
        title: mm + "/" + dd + "   " + week,
        key: workDate ,
        });

        //渲染对应数据
        if (this.employeeList.length > 0) {
        this.setTableColumn(this.employeeList[0], workDate , 0);
        }
        //开始时间加1天
        start = new Date(start.getTime() + 1 * 24 * 60 * 60 * 1000)
      
        if (start.getTime() <= end.getTime()) {
        this.addHead(start, end);
        }
    },
    //获取所有员工
    getAllEmployee() {    
      let that = this
      ajax.get('/api/services/app/EmployeeTaskMapping/GetAllEmployee').then(function (res) {
        that.employeeList = res.data.result
      })
    },
    ///设置当行（员工）某时间的班次
    setTableColumn(res, workDate , index) {
      this.checkEname = res.name
      this.checkKey = workDate 
      let that = this
      if (that.empAndDateList.length == 0) {
        //该人该时间没有工作
        that.$set(that.employeeList[index], workDate , '')
        index++
        if (index < that.employeeList.length) {
          that.setTableColumn(that.employeeList[index], workDate ,index)
        } else
          setTimeout(() => {
            that.loadingbut = false
          }, 500)
      } else {
        var task = that.empAndDateList[0].taskName
        that.$set(that.employeeList[index], workDate , task)
        index++
        if (index < that.employeeList.length) {
          that.setTableColumn(that.employeeList[index], workDate ,index)
        } else
          setTimeout(() => {
            that.loadingbut = false
          }, 500)
      }
    },
    ///将worktime转换成key值的格式
    getRowKey(headDate) {
      let yy = headDate.getFullYear();
      let mm = headDate.getMonth() + 1 < 10 ? '0' + (headDate.getMonth() + 1) : headDate.getMonth() + 1;
      let dd = headDate.getDate() < 10 ? '0' + headDate.getDate() : headDate.getDate();
      return yy + "-" + mm + "-" + dd;
    },
  },
   computed: {
    ///某员工某时间的排班
    empAndDateList() {
      return this.employeeListByName.filter((item) => {
        var tempDate = new Date(item.workTime)
        var tempDate = this.getRowKey(tempDate)

        return tempDate === this.checkKey
      })
    },
    ///某员工的所有排班
    employeeListByName() {
      return this.arrangeWorkOriginalList.filter((item) => {
        return item.employeeName === this.checkEname
      })
    },
  },
  beforeMount() {
    this.initArrangeWork();
    this.getAllTask();
    this.getAllEmployee()
  },
  created() {},
};
</script>

<style>
</style>